package com.cloud.drore.eboss.login;

import com.cloud.drore.eboos.common.constant.CommonConstant;
import com.cloud.drore.eboss.login.token.TokenManager;
import com.cloud.drore.eboss.login.token.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 浙江卓锐科技股份有限公司 版权所有 © Copyright 2018<br>
 *
 * @Description: <br>
 * @Project: eboos <br>
 * @CreateDate: Created in 2018/3/26 9:25 <br>
 * @Author: <a href="836327318@qq.com">吴昌益</a>
 */
@Component
public class RedisTokenManager implements TokenManager {

    private RedisTemplate redis;

    @Autowired
    @Qualifier("redisTemplate")
    public void setRedis(RedisTemplate redis) {
        this.redis = redis;
        //泛型设置成Long后必须更改对应的序列化方案
        redis.setKeySerializer(new JdkSerializationRedisSerializer());
    }

    public TokenModel createToken(long userId) {

        String token = (String) redis.boundValueOps(String.valueOf(userId)).get();

        if(token==null){
            //使用uuid作为源token
            token = UUID.randomUUID().toString().replace("-", "");
            //存储到redis并设置过期时间
        }

        TokenModel model = new TokenModel(userId, token);
        redis.boundValueOps(String.valueOf(userId)).set(token, CommonConstant.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return model;
    }

    public TokenModel getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        long userId = Long.parseLong(param[0]);
        String token = param[1];
        return new TokenModel(userId, token);
    }

    public boolean checkToken(TokenModel model) {
        if (model == null) {
            return false;
        }
        String token = (String) redis.boundValueOps(String.valueOf(model.getUserId())).get();
        if (token == null || !token.equals(model.getToken())) {
            return false;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        redis.boundValueOps(String.valueOf(model.getUserId())).expire(CommonConstant.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return true;
    }

    public void deleteToken(long userId) {
        redis.delete(String.valueOf(userId));
    }
}
